/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MainPack;

/**
 *
 * @author Van persie
 */
import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Graphics;
import MaterialPack.*;
import EntityGameObject.*;
import Supporter.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.media.MediaException;
import javax.obex.HeaderSet;
/**
 *
 * @author Van persie
 */
public  class PetManagement extends AbstractCanvas
{
    //private Image bufferGroup;
    private Vector groups;
    SubGroup ShopGroup = null;
    SubGroup SkillGroup = null;
    private boolean  isChanging = false;
    private int currentGrp;
    private int shrinkGrp;
    private int directChanging;
    private int xGroupPos;
    private int yGroupPos;
    private int widthGroup;
    private int heightGroup;
    
    // Control
    Button SpeedBtn = null;
    InfoPanel SpeedPnl = null;
    Button TongueLenBtn = null;
    InfoPanel TonguePnl = null;
    
    Button toPlayBtn = null;
    
    // animation
    private Timer timer ;        
    private Sticker sticker ;

    // List Item-Shop
    PetItem [] listItemShop = null;
    int NumOfItems = 0;
    
    boolean []CheckedItems = null;        
    int tempBill = 0;
    Vector listShop = null;
    
    // Pet 
    PetInstance petInstance = null;
    //Image Rule = null;
    InfoPanel MoneyLabel = null;
    InfoPanel MoneyVal = null;
    
    InfoPanel PointsLabel = null;
    InfoPanel PointsVal = null;
    
    InfoBar SpeedBar = null;
    
    int scalar = 40;
        
    // buffer 
    Vector listBackObjs;
    Image BufferImg = null;
    //Graphics BufferGraphics = null;
 
    public PetManagement(MainMIDlet midlet)
    { 
        
        main = midlet;

        //petInstance = new PetInstance("/PetPhoto.png", 2, 2, 40, 40, main.getPet());
        height = this.getHeight();
        width = this.getWidth();
        
                
        CheckedItems = new boolean[10];
        for(int i = 0; i < 10 ; i++ )
            CheckedItems[i] = false;
        
        listBackObjs = new Vector();
        LoadShopPrototype();
        
        try{
            if(width != height)
                LoadResource( );          
        }
        catch(Exception e)
        {}
        
        timer = new Timer();                
        
        //StartTimer();
    }

    
    public void LoadResource() throws IOException {
        

        
        ImageSupporter imgSupporter = new ImageSupporter();
        LoadPet();
        LoadBackground(imgSupporter);
        LoadManagementGroups(imgSupporter);     
        
        LoadPetInfo();   
        paintBackground();
        
    }

    public void LoadBackground(ImageSupporter imgSupporter) {
        // background & items in backgrounds
        // back buffer
        BufferImg = Image.createImage(width, height);
       //BufferGraphics = BufferImg.getGraphics();
                       
        Image temp = imgSupporter.getImage("/option-background.jpg");
        background = ImageSupporter.scaleImage(temp, width, height);
        //Rule = ImageSupporter.scaleImage(imgSupporter.getImage("/Rule.png"), 40, 2*height/3 ); 
        
        toPlayBtn = new Button("/Forward.png", null, 7*width/8 + 5 , 9*height/10 - 20, width/8, height/10);
        listBackObjs.addElement(toPlayBtn);
    }
    public void LoadShopGRP(Image plane,Image Act) {
        //       SHOP
        int wid = width /20;
        int hei = height/20;
                ShopGroup = new SubGroup(plane,Act,"SHOP",xGroupPos, yGroupPos,widthGroup , heightGroup);
                
                
                listShop = ShopGroup.getItems();
                if(!listShop.isEmpty())
                    listShop.removeAllElements();
               
               
                
                MoneyLabel = new  InfoPanel(null, "Money : ", xGroupPos + wid, yGroupPos + hei, 2*scalar, scalar,  Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
                MoneyLabel.setNoBackground(true);
                MoneyVal = new  InfoPanel(null,Integer.toString(petInstance.GetAttributes(Pet.MONEY)), xGroupPos + wid + 5*scalar/3, yGroupPos + hei, scalar,2*scalar/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
                MoneyVal.TransBackground(true);
                ShopGroup.Add(MoneyLabel);
                ShopGroup.Add(MoneyVal);
                

                   
                ShopGroup.Add(listItemShop[0]);
                ShopGroup.Add(listItemShop[2]);
                ShopGroup.Add(listItemShop[3]);
                ShopGroup.Add(listItemShop[1]);
                
                ShopGroup.ArrangeItem();
                
                groups.addElement(ShopGroup);
    }

    public void LoadSkillGRP(Image plane, Image Act) {
        // bufferGroup = ImageSupporter.alphaBlend(ImageSupporter.scaleImage(imgSupporter.getImage("/Plane.jpg"), widthGroup, heightGroup));
  
        int wid = width/20 ;
        int hei = height/20;
        
        ImageSupporter imgSpp = new ImageSupporter();
        Image button = imgSpp.getImage("/PlusBtn1.jpg");
 // SKILL
        SkillGroup = new SubGroup(plane,Act,"Skill ",xGroupPos, yGroupPos,widthGroup , heightGroup);

       
         PointsLabel = new InfoPanel(null, "Points : ",xGroupPos + wid , yGroupPos + hei, 80, scalar*2/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_LARGE));
             PointsLabel.setNoBackground(true);
             PointsLabel.setAnchorMode(InfoPanel.ANC_MIDDLE);
        PointsVal = new InfoPanel(null, Integer.toString(petInstance.GetAttributes(Pet.POINTS)) ,PointsLabel.getxPos() + PointsLabel.getWidth()/2 + 2*wid , PointsLabel.getyPos() + 2, scalar, scalar*2/3,  Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
            PointsVal.SetAlphaBack();
             PointsVal.TransBackground(true);
             PointsVal.setAnchorMode(InfoPanel.ANC_MIDDLE);
         
         SkillGroup.Add(PointsLabel);
         SkillGroup.Add(PointsVal);
         
        InfoPanel temp = null;
         SpeedBtn = new Button(button, null, xGroupPos + wid*3, yGroupPos + hei + scalar, scalar, scalar);
         
         temp = new InfoPanel(null, " Speed : ", SpeedBtn.getxPos() + SpeedBtn.getWidth()/2 + wid , SpeedBtn.getyPos() + SpeedBtn.getHeight() - 2*hei, 3*scalar/2, scalar*2/3,  Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
             temp.setNoBackground(true);
             temp.setAnchorMode(InfoPanel.ANC_LEFT);
         
         SpeedPnl = new InfoPanel(null,Integer.toString(petInstance.getSpeech()),temp.getxPos() + 6*wid,SpeedBtn.getyPos() + SpeedBtn.getHeight() - 7*hei/3, scalar, scalar*2/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
         SpeedPnl.SetAlphaBack();
         SpeedPnl.TransBackground(true);
         
         SkillGroup.Add(SpeedBtn);
         SkillGroup.Add(temp);           
         SkillGroup.Add(SpeedPnl);
         
         
         TongueLenBtn = new Button(button,null, xGroupPos + wid*3, yGroupPos + 2*(wid + scalar), scalar, scalar);
         temp = new InfoPanel(null, " Tongue : ", TongueLenBtn.getxPos() + TongueLenBtn.getWidth()/2 + wid , TongueLenBtn.getyPos() + TongueLenBtn.getHeight() - 2*hei, 2*scalar, scalar*2/3,  Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
             temp.setNoBackground(true);
             temp.setAnchorMode(InfoPanel.ANC_LEFT);
             
         //int a = petInstance.getTongueLen();
        TonguePnl = new InfoPanel(null, Integer.toString(petInstance.getTongueLen()), temp.getxPos() + 6*wid ,TongueLenBtn.getyPos() + TongueLenBtn.getHeight() - 7*hei/3, scalar, scalar*2/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
         TonguePnl.SetAlphaBack();
         TonguePnl.TransBackground(true);
         
         SkillGroup.Add(TongueLenBtn);
         SkillGroup.Add(temp);           
         SkillGroup.Add(TonguePnl);
         
        groups.addElement(SkillGroup);
    }

    public void LoadManagementGroups(ImageSupporter imgSupporter) {
        //group 
        
        xGroupPos =  scalar;
        yGroupPos = scalar/3;
        widthGroup = width-(2*scalar/3+2) ;
        heightGroup = height - (height/5 + scalar/4);
        
        
        if(groups != null)
            groups.removeAllElements();
        else
            groups = new Vector();
        
        Image plane = imgSupporter.getImage("/Plane.png");
        plane = ImageSupporter.transparent(ImageSupporter.alphaBlend(ImageSupporter.scaleImage(plane, widthGroup, heightGroup)));
        
        Image ActiveName = plane;
        
        // skill
        LoadSkillGRP(plane,ActiveName);
        // shop
        LoadShopGRP(plane,ActiveName);
        
        currentGrp = 0;
        ((SubGroup)groups.elementAt(currentGrp)).setIsVisible(true);
    }
    public void Reset()
    {
        LoadShopPrototype();
        if(!groups.isEmpty())
            groups.removeAllElements();
        //LoadShopGRP();
        for(int i = 0;i< CheckedItems.length; i++)
            CheckedItems[i] = false;
        tempBill = 0;
        LoadManagementGroups(new ImageSupporter());
        ShowPetInfo();
    }
    public void LoadShopPrototype()
    {
        NumOfItems = 5;
        listItemShop = new PetItem[NumOfItems];
        //for(int i = 0; i < 5 ; i++)
        Image checker = new ImageSupporter().getImage("/button-tick.png");
        
        listItemShop[0] = new PetItem("/chocolate.png",checker, "Socola",xGroupPos + 10, yGroupPos + 10, scalar , scalar,PetItem.TYPE_CHECK);
        listItemShop[1] = new PetItem("/vitamin.png",checker, "Vitamin",xGroupPos + 10, yGroupPos + 10, scalar , scalar,PetItem.TYPE_CHECK);
        listItemShop[2] = new PetItem("/strawberry.png",checker, "Strawberry",xGroupPos + 10, yGroupPos + 10, scalar , scalar,PetItem.TYPE_CHECK);
        listItemShop[3] = new PetItem("/milk.png",checker, "Milk",xGroupPos + 10, yGroupPos + 10, scalar , scalar,PetItem.TYPE_CHECK);
        listItemShop[4] = new PetItem("/banana.png",checker, "Banana",xGroupPos + 10, yGroupPos + 10, scalar , scalar,PetItem.TYPE_CHECK);
        
    }
    
    public void LoadPet() {
        // Pet photo
        
        Pet pet = main.getPet();
        petInstance = new PetInstance(width/6, height , width/3, height/4,main.getPet(),false);
        
        listBackObjs.addElement(petInstance);
     }
    
    public void LoadPetInfo()
    {
        
        int x = width/3 + 10;
        int y = 30;
        // set up

        
        InfoPanel temp;
        
        temp = new InfoPanel(null,"Level " + Integer.toString(petInstance.GetAttributes(Pet.LEVEL)),petInstance.getxPos() + petInstance.getWidth()/2 , petInstance.getyPos() - petInstance.getHeight() + 10, scalar*3, scalar*2/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_LARGE));
        temp.setNoBackground(true);
        temp.setAnchorMode(InfoPanel.ANC_LEFT);
        listBackObjs.addElement(temp);
        
        
        temp = new InfoPanel(null, "Speed ",petInstance.getxPos() + petInstance.getWidth()/2 ,petInstance.getyPos()- petInstance.getHeight() + scalar , 2*scalar, scalar*2/3, Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN  ,Font.SIZE_MEDIUM));
        temp.setNoBackground(true);
        temp.setAnchorMode(InfoPanel.ANC_LEFT);
        listBackObjs.addElement(temp);
        
        
        SpeedBar = new InfoBar("/option-expbar.png","/option-expbar-mask.png", InfoBar.HORIZON, petInstance.GetAttributes(Pet.SPEED)*10,petInstance.getxPos() + petInstance.getWidth()/2 ,petInstance.getyPos()-petInstance.getHeight() + 9*scalar/8 + 15 , 127, 14);
        SpeedBar.SetColor(255, 0, 0);
        listBackObjs.addElement(SpeedBar);
    }

    public void ShowPetInfo() {
        PointsVal.setText(Integer.toString(petInstance.GetAttributes(Pet.POINTS)));
        SpeedPnl.setText(Integer.toString(petInstance.GetAttributes(Pet.SPEED)));
        SpeedBar.setRatio(petInstance.GetAttributes(Pet.SPEED)*10);
        TonguePnl.setText(Integer.toString(petInstance.GetAttributes(Pet.TONGUELEN)));
        MoneyVal .setText(Integer.toString(petInstance.GetAttributes(Pet.MONEY)- tempBill));
        paintBackground();
    }

    protected void keyReleased(int key)
    {
        int n = groups.size();
        switch(key)
        {
            case KEY_NUM4:
            case LEFT:
                if(isChanging)
                    Skip();
                shrinkGrp = currentGrp;
                currentGrp = (currentGrp - 1 + n)%n;
                Change(Graphics.LEFT);  
                break;
               
            case KEY_NUM6:
            case RIGHT:
                if(isChanging)
                    Skip();
                shrinkGrp = currentGrp;
                currentGrp = (currentGrp + 1)%n;
                Change(Graphics.RIGHT);
                
                break;
            case KEY_NUM0:
                main.exitMIDlet();
                break;
        }
        repaint();
    }
    public void Skip()
    {
        ((SubGroup)groups.elementAt(shrinkGrp)).setIsVisible(false);
        ((SubGroup)groups.elementAt(currentGrp)).setIsVisible(true);
        isChanging = false;
    }
    public void Change(int direction) {
                
        ((SubGroup)groups.elementAt(shrinkGrp)).Back();        
        ((SubGroup)groups.elementAt(currentGrp)).Front();
        directChanging = direction;
        StartTimer();
    }
    protected void sizeChanged(int w, int h)
    {
  
        width = w;
        height = h;
        if(listBackObjs != null)
            listBackObjs.removeAllElements();
        try{
            LoadResource();            
        }
        catch(Exception e)
        {
            System.out.println("error in size changed ! ");
        }
        
    }
    protected void pointerDragged(int x, int y)
    {

    }

    protected void pointerPressed(int x, int y)
    {
         
         for(int i=0; i <groups.size(); i++)
             ((MaterialObject)groups.elementAt(i)).Press(x,y);
         for(int j=0; j <listBackObjs.size(); j++)
             ((MaterialObject)listBackObjs.elementAt(j)).Press(x,y);
         paintBackground();
         repaint();
    }
    protected void pointerReleased (int x, int y)
    {
//        for(int i=0; i <listObjects.size(); i++)
//            ((MaterialObject)listObjects.elementAt(i)).Release(x,y);
        if(toPlayBtn.Release(x, y))
        {
                try {
                    main.SwitchTo(5);
                } catch (IOException ex) {
                    ex.printStackTrace();
                } catch (MediaException ex) {
                    ex.printStackTrace();
                }
            
        }
        
        

        if(SpeedBtn.Release(x, y) && petInstance.GetAttributes(Pet.POINTS) > 0 )
        {
            petInstance.AddAttributes(Pet.SPEED, 1);
            petInstance.AddAttributes(Pet.POINTS, -1);
            ShowPetInfo();
            
        }
        
        if(TongueLenBtn.Release(x, y) && petInstance.GetAttributes(Pet.POINTS) > 0)
        {
            petInstance.AddAttributes(Pet.TONGUELEN, 1);
            petInstance.AddAttributes(Pet.POINTS, -1);
            ShowPetInfo();
        }

        if(petInstance.Release(x, y))
        {
            // draw something
            
            for(int i = 0; i < CheckedItems.length; i++)
            {
                if(CheckedItems[i] == true)                   
                {
                    petInstance.AddItem((PetItem)listShop.elementAt(i));
                    CheckedItems[i] = false;
                }
            }
            
           paintBackground();  
                try {
                    // do something
                    main.SwitchTo(MainMIDlet.SCENE_PLAYPET);
                } catch (IOException ex) {
                    ex.printStackTrace();
                } catch (MediaException ex) {
                    ex.printStackTrace();
                }
            
        }
        SubGroup grp = null;
        for(int i=0; i <groups.size(); i++)        
        {
            grp = ((SubGroup)groups.elementAt(i));
            if( grp.Release(x,y))
            {
                if(isChanging)
                    Skip();
                shrinkGrp = currentGrp;
                currentGrp = (currentGrp + 1)%groups.size();
                Change(Graphics.RIGHT);
            }
            if(grp.getItems().size() > 0)
            {
                for(int j = 0; j <grp.getItems().size() ; j++ )
                    if(((PetItem)grp.getItems().elementAt(j)).Release(x, y)  )
                    {
                        if(((PetItem)grp.getItems().elementAt(j)).isActived() == false )
                        {
                            if(petInstance.GetAttributes(Pet.MONEY) >(((PetItem)grp.getItems().elementAt(j)).getPrice() + tempBill))
                            {
                                //petInstance.BuyItem(((PetItem)grp.getItems().elementAt(j)));
                                CheckedItems[j] = true;
                                tempBill += ((PetItem)grp.getItems().elementAt(j)).getPrice();
                                ((PetItem)grp.getItems().elementAt(j)).setActived(true);
                            }
                        }
                        else 
                        {
                            //petInstance.ReturnItem(((PetItem)grp.getItems().elementAt(j)));
                            CheckedItems[j] = false;
                            tempBill -= ((PetItem)grp.getItems().elementAt(j)).getPrice();
                            ((PetItem)grp.getItems().elementAt(j)).setActived(false);
                        }
                        ShowPetInfo();
                    }
            }
        }
        repaint();
    }


    public void commandAction(Command command, Displayable displayable)
    {
        
    }
    
    public void TimerStick()
    {        
        boolean bool1 = ((SubGroup)groups.elementAt(currentGrp)).Expand(directChanging);
        boolean bool2 = ((SubGroup)groups.elementAt(shrinkGrp)).Shrink(directChanging);
        if(bool1 == true || bool2 == true)
        {
            PauseTimer();
            System.out.println("Finish ");
            
        } 
        repaint();
    }
    public void paint(Graphics g )
    {
        
        g.drawImage(BufferImg, 0, 0, Graphics.TOP | Graphics.LEFT);
//        for(int i=0; i <listObjects.size(); i++)
//            ((MaterialObject)listObjects.elementAt(i)).paint(g);
        for(int i = 0; i < groups.size();i++)
            ((MaterialObject)groups.elementAt(i)).paint(g);
        //toPlayBtn.paint(g);
    }
    public void paintBackground()
    {
        
        Graphics BufferGraphics = BufferImg.getGraphics();
        BufferGraphics.fillRect(0, 0, width, height);
        BufferGraphics.drawImage(background, 0, 0,Graphics.TOP | Graphics.LEFT);
        //toPlayBtn.paint(BufferGraphics);
        for(int i=0; i <listBackObjs.size(); i++)
            ((MaterialObject)listBackObjs.elementAt(i)).paint(BufferGraphics);
        
    }
    public void StartTimer() {
        sticker = new Sticker();        
        timer.schedule(sticker, 50,50);
        isChanging = true;
    }
    public void PauseTimer()
    {
        sticker.cancel();
        isChanging = false;
    }
    
        
    class Sticker extends TimerTask
        {
            public void run()
            {
                TimerStick();
                repaint();
                
            }
        }
}
